package com.mashibing.topic;
import com.mashibing.util.RabbitMQConnectionUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;

/**
 * 消息发布者类，用于向RabbitMQ发送消息
 */
public class Publisher {
    // 交换机名称
    public static final String EXCHANGE_NAME = "topic";
    // 第一个队列名称
    public static final String QUEUE_NAME1="topic-one";
    // 第二个队列名称
    public static final String QUEUE_NAME2="topic-two";

    /**
     * 发布消息到RabbitMQ的测试方法
     * @throws Exception 当与RabbitMQ的连接或消息发送过程中出现问题时抛出异常
     */
    @Test
    public void publish() throws Exception {
        //1.获取连接对象
        Connection connection = RabbitMQConnectionUtil.getConnection();
        //2.构建channel
        Channel channel = connection.createChannel();

        //3.构建交换机，类型为TOPIC，即主题式交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        //4.构建队列，声明两个队列，不持久化，独占，非自动删除
        channel.queueDeclare(QUEUE_NAME1,false,false,false,null);
        channel.queueDeclare(QUEUE_NAME2,false,false,false,null);
        //5.绑定交换机和队列，使用不同的路由键，因为是主题模式
        channel.queueBind(QUEUE_NAME1,EXCHANGE_NAME,"*.orange.*");
        channel.queueBind(QUEUE_NAME2,EXCHANGE_NAME,"*.*.rabbit");
        channel.queueBind(QUEUE_NAME2,EXCHANGE_NAME,"lazy.#");

        //6.发消息到交换机，使用不同的路由键，因为是主题模式
        channel.basicPublish(EXCHANGE_NAME,"big.orange.rabbit",null,"大橙子".getBytes());
        channel.basicPublish(EXCHANGE_NAME,"small.white.rabbit",null,"小白兔".getBytes());
        channel.basicPublish(EXCHANGE_NAME,"lazy.dog.dog.dog",null,"大懒狗".getBytes());
        System.out.println("消息发送成功");
    }
}
